# -*- coding: utf-8 -*-
# @Time: 2021/11/5 21:23
# @Author: jiuwu
# @Email: 2359196586@qq.com
# @File: serializers.py
# @Software: PyCharm
import re

from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from users.models import UserDetail, Area, Address


class UserDetailSerializer(ModelSerializer):  # 详情信息序列化器
    class Meta:
        model = UserDetail
        fields = '__all__'
        extra_kwargs = {
            'avatar': {'read_only': True},
            'user': {'write_only': True}
        }


class UserSerializer(ModelSerializer):
    userdetail = UserDetailSerializer(required=False, read_only=True)

    class Meta:
        model = User
        exclude = ['password', 'last_name', 'user_permissions']

        extra_kwargs = {  # 不让你修改 但是要映射
            'last_login': {'read_only': True},
            'is_superuser': {'read_only': True},
            'is_staff': {'read_only': True},
            'is_active': {'read_only': True},
            'date_joined': {'read_only': True},
            'groups': {'read_only': True},

        }


# 学生注册
class CreateUserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'email']

        extra_kwargs = {  # 后端校验主要是防内行
            'first_name': {
                'required': True
            },
            'email': {
                'required': True
            }
        }


class AreaSerializer(ModelSerializer):
    class Meta:
        model = Area
        fields = ['id', 'name']


class AreaSonSerializer(ModelSerializer):
    # set管理器 关联序列化器
    # 模型类名小写_set
    area_set = AreaSerializer(many=True, read_only=True)

    class Meta:
        model = Area
        fields = '__all__'
        # exclude = ['parent']


class AddressSerializer(ModelSerializer):
    province_name = serializers.CharField(source='province.name', read_only=True)
    city_name = serializers.CharField(source='city.name', read_only=True)
    district_name = serializers.CharField(source='district.name', read_only=True)

    class Meta:
        model = Address
        exclude = ['is_delete']

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式错误')
        return value
